#include "XSSL.h"
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <iostream>
using namespace std;
XSSL::XSSL()
{
}

XSSL::~XSSL()
{
}

bool XSSL::Accept()
{
    if (!ssl_)
    {
        return false;
    }
    if (SSL_accept(ssl_) == 1)
    {
        // 连接成功后，打印加密器信息
        PrintCipher();
        PrintPeerCert();
        return true;
    }
    return false;
}

bool XSSL::Connect()
{
    // 检查SSL对象是否已创建
    if (!ssl_)
    {
        return false;
    }
    
    // 尝试建立SSL连接
    int ret = SSL_connect(ssl_);
    // 如果连接失败，输出错误信息并返回false
    if (ret != 1)
    {
        cout << "XSSL::Connect connect error" << endl;
        ERR_print_errors_fp(stderr);
        return false;
    }
    cout << "XSSL::Connect connect succeed" << endl;
    // 连接成功后，打印加密器信息
    PrintCipher();
    PrintPeerCert();
    return true;
}

void XSSL::PrintCipher()
{
    if (!ssl_)
    {
        return;
    }
    cout << "cipher:" << SSL_CIPHER_get_name(SSL_get_current_cipher(ssl_)) << endl;
}

void XSSL::PrintPeerCert()
{
    if(!ssl_)return;
    auto cert = SSL_get_peer_certificate(ssl_);
    if (cert)
    {
        cout << "peer cert:" << X509_NAME_oneline(X509_get_subject_name(cert), 0, 0) << endl;
        auto issuer = X509_get_issuer_name(cert);
        if (issuer)
        {
            cout << "issuer:" << X509_NAME_oneline(issuer, 0, 0) << endl;
        }
        X509_free(cert);
    }
}

int XSSL::Read(char *buf, int len)
{
    if(!ssl_)
        return -1;
    return SSL_read(ssl_, buf, len);
}

int XSSL::Write(const char *buf, int len)
{
    if(!ssl_)
        return -1;
    return SSL_write(ssl_, buf, len);
}

void XSSL::Close()
{
    if(ssl_){
        SSL_shutdown(ssl_);
        SSL_free(ssl_);
        ssl_ = nullptr;
    }
}
